package animix.blue.server.zuul.component;

import animix.blue.server.common.bean.pojo.Result;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;

/**
 * 登陆Filter
 */
@Component
public class LoginFiler extends ZuulFilter {

    private static Logger logger = LoggerFactory.getLogger(LoginFiler.class);
    private static final List<String> ALLOW_PATHS = Arrays.asList("/api/us/user/login", "/api/us/user/info/", "/api/us/user/logout",
            "/api/us/v2/api-docs", "/api/ls/v2/api-docs");

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        logger.info("**** LoginFiler Begin ***********************************************");
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        logger.info(request.getMethod() + ": " + request.getRequestURI());
        // 不拦截
        if (contains(request.getRequestURI())) {
            logger.info("**** LoginFiler End Allowed *****************************************");
            return null;
        }
        // 跨域验证的第一次请求
        if (request.getMethod().equals("OPTIONS")) {
            return null;
        }
        // 从Header中取token
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            // 参数中再取一次
            token = request.getParameter("token");
        }
        if (StringUtils.isBlank(token)) {
            // 拦截
            return intercept(requestContext);
        }
        // 取到token，调用User服务判断用户是否登陆
        Result result = restTemplate.getForObject("http://BLUE-SERVER-USER/user/info/" + token, Result.class);
        if (result.getCode() != 200) {
            // 拦截
            return intercept(requestContext);
        }
        // 放行
        logger.info("**** LoginFiler End Passed ******************************************");
        return null;
    }

    /**
     * 放行URI判断
     */
    private boolean contains(String uri) {
        ListIterator<String> iterator = ALLOW_PATHS.listIterator();
        while (iterator.hasNext()) {
            String path = iterator.next();
            if (uri.length() >= path.length() && path.equals(uri.substring(0, path.length())))
                return true;
        }
        return false;
    }

    /**
     * 拦截处理
     */
    private Object intercept(RequestContext requestContext) {
        requestContext.setSendZuulResponse(false);
        requestContext.setResponseStatusCode(401);
        requestContext.setResponseBody(JSON.toJSONString(Result.build(401, "token invalid")));
        requestContext.getResponse().setContentType("application/json;charset=UTF-8");
        logger.info("**** LoginFiler End Intercepted *************************************");
        return null;
    }
}
